<?php
namespace app\homes\controller;
use app\homes\controller\Base;
use think\Session;
use think\Request;
class Order extends Base{
	
	public function export()
	{
		//if(Request::instance()->isAjax()){
			$this->POWER();
			$datetime = input("datetime");
			$_datetime = explode(" - ",$datetime);
			$order = Db("order")
				->alias("o")
				->join("__WAREHOUSE__ w","w.w_id = o.w_id")
				->where("o.sub_id = ".$this->__WEB_CONFIG__['sub_id']." and o.u_id = ".session("user_id_".$this->__WEB_CONFIG__['sub_id'])." and o.o_addtime between '".trim($_datetime[1])." 00:00:00' and '".trim($_datetime[1])." 23:59:59'")->select();
			import('PHPExcel.PHPExcel/IOFactory');
			import('PHPExcel.PHPExcel');
			import('PHPExcel.PHPExcel/Writer/Excel2007');
			$header_arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
			$template = _PATH_.'/template_home.xls';          //使用模板  
			$objPHPExcel = \PHPExcel_IOFactory::load($template);     //加载excel文件,设置模板  
			$objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);  //设置保存版本格式  
			if(empty($filename)) $filename = time();
			//接下来就是写数据到表格里面去  
			$objActSheet = $objPHPExcel->getActiveSheet();  
			
			$count = count($order);
			$for_i = 2;
			for($i=0;$i<$count;$i++){
				$objActSheet->setCellValue('A'.$for_i,$order[$i]['o_sncode']);
				$objActSheet->setCellValue('G'.$for_i,$order[$i]['w_content']);
				$objActSheet->setCellValue('H'.$for_i,$order[$i]['o_kddh_sncode']);
				$for_i = $for_i + 1;
			}
				
			header("Pragma: public");  
			header("Expires: 0");  
			header("Cache-Control:must-revalidate, post-check=0, pre-check=0");  
			header("Content-Type:application/force-download");  
			header("Content-Type:application/vnd.ms-execl");  
			header("Content-Type:application/octet-stream");  
			header("Content-Type:application/download");;  
			header('Content-Disposition:attachment;filename="'.$filename.'.xls"');  
			header("Content-Transfer-Encoding:binary");  
			$objWriter->save('php://output');
		//}
		
	}
	
	public function index()
	{
		$this->POWER();
		$userinfo = Db("users")
					->alias("u")
					->join("__USER_GROUP__ ug","ug.ug_id = u.ug_id","left")
					->where("u.sub_id = ".$this->__WEB_CONFIG__['sub_id']." and u.u_id = ".session("user_id_".$this->__WEB_CONFIG__['sub_id']))->find();
		$this->assign("userinfo",$userinfo);
		
		$order = Db("order")
			->alias("o")
			->join("__SUBSTATION__ s","o.sub_id = s.sub_id","left") //所属分站
			->join("__USERS__ u","o.u_id = u.u_id","left") //所属用户
			->join("__GIFT__ g","o.gift_id = g.gift_id ","left") //所属礼物
			->join("__WAREHOUSE__ w","o.w_id = w.w_id","left") //所属仓库
			->join("__PLATFORM__ pf","o.pf_id = pf.pf_id","left") //所属电商平台
			->where("o.sub_id = ".$this->__WEB_CONFIG__['sub_id']." and o.u_id = ".session("user_id_".$this->__WEB_CONFIG__['sub_id']))
			->order("o_id desc")
			->paginate(20);
		$page = $order->render();
		$this->assign('page', $page);
		$this->assign("order",$order);
		return view();		
	}
	
	public function buy()
	{
		$this->POWER();
		$userinfo = Db("users")
					->alias("u")
					->join("__USER_GROUP__ ug","ug.ug_id = u.ug_id","left")
					->where("u.sub_id = ".$this->__WEB_CONFIG__['sub_id']." and u.u_id = ".session("user_id_".$this->__WEB_CONFIG__['sub_id']))->find();
		$this->assign("userinfo",$userinfo);
		
	
		
		$id = input("id");
		//查出商品信息
		$gift = Db("gift")->where("gift_id = {$id} and gift_status = 1")->find();
		if(empty($gift)){
			echo "礼物不存在！";
			exit;
		}
		
		if(empty($gift['w_id'])){
			echo "此商品不存在仓库，请与管理员联系！";
			exit;
		}
		//查出仓库
		$gift['w_id'] = substr($gift['w_id'],0,strlen($gift['w_id'])-1); 
		$war = Db("warehouse")->where("w_status = 1 and pf_id <> '' and w_id in ({$gift['w_id']})")->select();
		
		//查出电商
		$war[0]['pf_id'] = substr($war[0]['pf_id'],0,strlen($war[0]['pf_id'])-1); 
		$platform = Db("platform")->where("pf_status = 1 and pf_id in ({$war[0]['pf_id']})")->select();
		
		//查出第一个仓库的默认价格
		$freight = Db("freight")->where("sub_id = ".$this->__WEB_CONFIG__['sub_id']." and ug_id = {$userinfo['ug_id']} and w_id = {$war[0]['w_id']}")->find();
		$this->assign("freight",$freight);
		$this->assign("gift",$gift);
		$this->assign("war",$war);
		$this->assign("platform",$platform);
		return view();
	}


	
	public function change()
	{
		$this->POWER();
		if(Request::instance()->isAjax()){
			$id = input("id");
			$userinfo = Db("users")
					->alias("u")
					->join("__USER_GROUP__ ug","ug.ug_id = u.ug_id","left")
					->where("u.sub_id = ".$this->__WEB_CONFIG__['sub_id']." and u.u_id = ".session("user_id_".$this->__WEB_CONFIG__['sub_id']))->find();
			
			//查出仓库
			$war = Db("warehouse")->where("w_status = 1 and pf_id <> '' and w_id = {$id}")->find();
			
			//查出第一个仓库的默认价格
			$freight = Db("freight")->where("sub_id = ".$this->__WEB_CONFIG__['sub_id']." and ug_id = {$userinfo['ug_id']} and w_id = {$war['w_id']}")->find();
			
			//查出电商
			$war['pf_id'] = substr($war['pf_id'],0,strlen($war['pf_id'])-1); 
			$platform = Db("platform")->where("pf_status = 1 and pf_id in ({$war['pf_id']})")->select();
			
			$json['platform'] = $platform;
			$json['freight'] = $freight;
			echo json_encode($json);
			exit;

			
		}
	}
	
	public function addbuy()
	{
		$this->POWER();
		if(Request::instance()->isAjax()){
			$giftid   = input("giftid");
			$store_id = input("store_id");
			$plattype = input("plattype");
			$addstext = input("addstext");
			
			//批量上传功能
			$xdtype = input("xdtype");
			$avatar = input("avatar");
			//批量上传功能
			
			if($xdtype==1){
				$arr      = explode("\n",$addstext);
				$count    = count($arr);
				if(empty($addstext)){
					eyJson("收货地址不能为空！");
				}
			}else{
				$xlsPath = _PATH_ . $avatar; //指定要读取的exls路径
				import('PHPExcel.PHPExcel');
				import('PHPExcel.PHPExcel/IOFactory');
				$inputFileType = \PHPExcel_IOFactory::identify($xlsPath);
				$xlsReader = \PHPExcel_IOFactory::createReader($inputFileType);
				$xlsReader->setReadDataOnly(true);
				$xlsReader->setLoadSheetsOnly(true);
				$Sheets = $xlsReader->load($xlsPath);
				//开始读取
				$Sheet = $Sheets->getSheet(0)->toArray();
				if(empty($Sheet[0][0])){
					eyJson("收货地址不能为空！");
				}

				if($Sheet[0][0]!="订单号" or $Sheet[0][1]!="收货人" or $Sheet[0][2]!="省" or $Sheet[0][3]!="市" or $Sheet[0][4]!="区" or $Sheet[0][5]!="街道" or $Sheet[0][6] != "手机"){
					eyJson("请按格式提交数据！");
				}
				$count =  count($Sheet)-1;
				for($i=1;$i<=$count;$i++){
					$i1 = $i-1;
					$arr[$i1] = $Sheet[$i][1]."，".$Sheet[$i][6]."，".$Sheet[$i][2].$Sheet[$i][3].$Sheet[$i][4].$Sheet[$i][5];
				}
			}
			
			$userinfo = Db("users")
					->alias("u")
					->join("__USER_GROUP__ ug","ug.ug_id = u.ug_id","left")
					->where("u.sub_id = ".$this->__WEB_CONFIG__['sub_id']." and u.u_id = ".session("user_id_".$this->__WEB_CONFIG__['sub_id']))->find();
					
			if(empty($userinfo['u_send_name']) or empty($userinfo['u_send_phone'])){
				eyJson("请先设置发货人信息！");
			}
			
			$gift = Db("gift")->where("gift_status = 1 and gift_id = {$giftid}")->find();
			$freight = Db("freight")->where("sub_id = ".$this->__WEB_CONFIG__['sub_id']." and ug_id = {$userinfo['ug_id']} and w_id = {$store_id}")->find();
			
			$o_zmoney = $freight['f_money'] + $gift['gift_money']; //此单价格
			
			//处理余额是否足够
			$zyo_zmoney = $o_zmoney * $count;
			if($zyo_zmoney > $userinfo['u_balance']){
				eyJson("余额不足，请先充值！");
			}
			//处理余额是否足够
			
			$MODEL_DATA = array(
				'sub_id'        => $this->__WEB_CONFIG__['sub_id'],
				'u_id'          => session("user_id_".$this->__WEB_CONFIG__['sub_id']),
				'gift_id'       => $giftid,
				'w_id'          => $store_id,
				'pf_id'         => $plattype,
				'o_addtime'     => date("Y-m-d H:i:s"),
				'o_gift_money'  => $gift['gift_money'],
				'o_count'       => 1,
				'o_money'       => $gift['gift_money'],
				'o_fa_name'     => $userinfo['u_send_name'],
				'o_fa_phone'    => $userinfo['u_send_phone'],
				'o_status'      => 1, //等待出单
				'o_zmoney'      => $o_zmoney,
				'o_kd_money'    => $freight['f_money'],
			);
			
			
			$warehouse = Db("warehouse")->where("w_id = {$store_id}")->find();
			if($warehouse['w_fahuo'] == 2){ //快宝发货
				import('Kuaidihelp.Kuaidihelp');
				$ss = new \Kuaidihelp;
				$ss->appid           = $this->__CONFIG__['s_kuaidihelp_appid'];
				$ss->appkey          = $this->__CONFIG__['s_kuaidihelp_appkey'];
				$ss->agent_id        = $warehouse['w_agent_id'];
				$ss->cp_code         = $warehouse['w_cp_code'];
				$ss->goods_name      = $gift['gift_title'];
				$ss->sender_phone    = $warehouse['w_sender_phone'];
				$ss->sender_name     = $warehouse['w_sender_name'];
				$ss->sender_province =  $warehouse['w_sender_province'];
				$ss->sender_city     = $warehouse['w_sender_city'];
				$ss->sender_district =  $warehouse['w_sender_district'];
				$ss->sender_detail   =  $warehouse['w_address'];	
			}
			
			for($i=0;$i<$count;$i++){
				$order_arr = explode("，",$arr[$i]);
				$MODEL_DATA['o_sncode']      = "EY".$this->makeRand(10);
				$MODEL_DATA['o_sho_name']    = $order_arr[0];
				$MODEL_DATA['o_sho_phone']   = $order_arr[1];
				$MODEL_DATA['o_sho_address'] = $order_arr[2];
				//快宝发货
				if($warehouse['w_fahuo'] == 2){
					//分割地址
					$address = $MODEL_DATA['o_sho_address'];
					preg_match('/(.*?(省|自治区|北京市|天津市))/', $address, $matches);
					if (count($matches) > 1) {
						$province = $matches[count($matches) - 2];
						$address = str_replace($province, '', $address);
					}
					preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
					if (count($matches) > 1) {
						$city = $matches[count($matches) - 2];
						$address = str_replace($city, '', $address);
					}
					preg_match('/(.*?(区|县|镇|乡|街道))/', $address, $matches);
					if (count($matches) > 1) {
						$area = $matches[count($matches) - 2];
						$address = str_replace($area, '', $address);
					}		
					//分割地址
					$ss->tid                = $MODEL_DATA['o_sncode'];
					$ss->recipient_phone    = $MODEL_DATA['o_sho_phone'];
					$ss->recipient_name     = $MODEL_DATA['o_sho_name'];
					$ss->recipient_province = $province;
					$ss->recipient_city     = $city;
					$ss->recipient_district = $area;
					$ss->recipient_detail   = $address;
					$ss->GetSheet();
					$ss->GetSheetError();
					if($ss->error == "ok"){
						$MODEL_DATA['o_status']      = 2;
						$MODEL_DATA['o_kddh_sncode'] = $ss->error_msg;
					}else{
						$MODEL_DATA['o_content'] = "快宝提示：".$ss->error_msg;
					}
				}
				//快宝发货
				$res = Db("order")->insert($MODEL_DATA);
				if($res){
					//下单成功，扣除用户余额，写入资金表
					$user = Db("users")->where("u_id = '{$userinfo['u_id']}'")->find();
					$USERS_DATA_1 = array(
						'u_balance' => $user['u_balance'] - $o_zmoney,
					);
					Db("users")->where("u_id = '{$userinfo['u_id']}'")->update($USERS_DATA_1);
					write_acpital($userinfo['u_id'],$userinfo['sub_id'],2,$o_zmoney,$MODEL_DATA['o_sncode']."订单支出",2,1);
				}
			}
			eyJson("下单成功！","success");
		}
	}
	
	
	//8-12位随机数
	public function makeRand($num=8){
			$strand = (double)microtime() * 1000000;
			if(strlen($strand)<$num){
					$strand = str_pad($strand,$num,"0",STR_PAD_LEFT);
			}
		   //return date('YmdHis').$third;
		   return $strand;
	} 
	

}